/*
 * Copyright 2006-2023 ahtelit.com, All Rights Reserved.
 */

package com.telit.android.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.telit.android.dto.easyexcel.CommFireAlarmsExcelDTO;
import com.telit.android.dto.easyexcel.HistoryFireAlarmsExcelDTO;
import com.telit.android.service.ExportService;
import com.telit.common.entity.DataReturn;
import com.telit.common.entity.PageData;
import com.telit.common.enums.ResultCode;
import com.telit.common.exception.ForestBaseException;
import com.telit.firecommand.entity.CommFireAlarm;
import com.telit.firecommand.feign.RemoteFirecommandService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * ExportServiceImpl
 *
 * @author yuezhuang
 * @since 2023-03-10
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ExportServiceImpl implements ExportService {

    private final RemoteFirecommandService remoteFirecommandService;

    /**
     * 导出历史火情列表
     */
    @Override
    public void exportHistoryFireList(String startTime, String endTime, String districtCode, String fireLevel,
                                      String resource, HttpServletResponse response) throws IOException {
        try {
            DataReturn<PageData<List<CommFireAlarm>>> pageDataDataReturn = remoteFirecommandService.queryAllHistoryFire(
                    startTime, endTime, districtCode, fireLevel, resource, 1, Integer.MAX_VALUE);
            if (!ResultCode.SUCCESS.getCode().equals(pageDataDataReturn.getCode())) {
                throw new ForestBaseException(pageDataDataReturn.getErrorMsg());
            }
            PageData<List<CommFireAlarm>> pageData = pageDataDataReturn.getData();
            List<HistoryFireAlarmsExcelDTO> data = new ArrayList<>();
            List<CommFireAlarm> list = pageData.getDatas();
            int size = list.size();
            for (int i = 0; i < size; i++) {
                data.add(HistoryFireAlarmsExcelDTO.builder()
                        .num(i + 1)
                        .findTime(list.get(i).getFindTime())
                        .fireLevel(list.get(i).getFireLevel())
                        .districtName(list.get(i).getDistrictName())
                        .detailAddress(list.get(i).getDetailAddress())
                        .longitudeAndLatitude(list.get(i).getLongitude() + "," + list.get(i).getLatitude())
                        .source(list.get(i).getResource())
                        .sourceName(list.get(i).getFinderName())
                        .recieverName(list.get(i).getRecieverName())
                        .build());
            }

            String fileName = URLEncoder.encode(String.valueOf(System.currentTimeMillis()),
                    StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), HistoryFireAlarmsExcelDTO.class).autoCloseStream(
                    Boolean.FALSE).sheet("火情列表").doWrite(data);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("code", "500");
            map.put("errorMsg", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    /**
     * 导出火情列表
     */
    @Override
    public void exportFireList(String status, String startTime, String endTime, String districtCode, String resource,
                               HttpServletResponse response) throws IOException {
        try {
            if (StrUtil.isEmpty(startTime) && StrUtil.isEmpty(endTime)) {
                startTime = DateUtil.format(DateUtil.lastMonth(), DatePattern.NORM_DATETIME_PATTERN);
                endTime = DateUtil.now();
            }

            DataReturn<PageData<List<CommFireAlarm>>> pageDataDataReturn = remoteFirecommandService.queryAllFireByCondition(
                    status, startTime, endTime, districtCode, resource, null, null, 1, Integer.MAX_VALUE);
            if (!ResultCode.SUCCESS.getCode().equals(pageDataDataReturn.getCode())) {
                throw new ForestBaseException(pageDataDataReturn.getErrorMsg());
            }
            PageData<List<CommFireAlarm>> pageData = pageDataDataReturn.getData();
            List<CommFireAlarmsExcelDTO> data = new ArrayList<>();
            List<CommFireAlarm> list = pageData.getDatas();
            int size = list.size();
            for (int i = 0; i < size; i++) {
                data.add(CommFireAlarmsExcelDTO.builder()
                        .num(i + 1)
                        .status(list.get(i).getStatus())
                        .findTime(list.get(i).getFindTime())
                        .districtName(list.get(i).getDistrictName())
                        .detailAddress(list.get(i).getDetailAddress())
                        .longitudeAndLatitude(list.get(i).getLongitude() + "," + list.get(i).getLatitude())
                        .source(list.get(i).getResource())
                        .sourceName(list.get(i).getFinderName())
                        .content(list.get(i).getContent())
                        .build());
            }

            String fileName = URLEncoder.encode(String.valueOf(System.currentTimeMillis()),
                    StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), CommFireAlarmsExcelDTO.class)
//                    .relativeHeadRowIndex(1)
//                    .registerWriteHandler(new HeaderSheetWriteHandler("火情信息"))
                    .autoCloseStream(Boolean.FALSE).sheet("火情列表").doWrite(data);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("code", "500");
            map.put("errorMsg", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

}
